package com.tjetc.output;

import org.junit.jupiter.api.Test;

import java.io.*;

public class _1FileOutputStream {
    /*
        字节输出流：FileOutputStream
        要求: 请使⽤ FileOutputStream 在 2.txt ⽂件， 中写⼊“hello ，world ”。
     */

    @Test
    public void testFileOutputStream() throws IOException {
        // 当文件不存在的时候 会自动创建
        // 如果需要追加而不是覆盖 设置第二个参数为true
        OutputStream outputStream =
                new FileOutputStream("/Users/gaoyongxiang/百度网盘/IDEA-Java/202507-java-se/chapter16/file/2.txt", true);
        // write 默认是覆盖写
        outputStream.write('a');
//        outputStream.write('a');
        outputStream.close();
    }


    @Test
    public void testFileOutputStream1() throws IOException {

        OutputStream outputStream =
                new FileOutputStream("/Users/gaoyongxiang/百度网盘/IDEA-Java/202507-java-se/chapter16/file/2.txt", true);
        String str = "hello, world";
        outputStream.write(str.getBytes());
        outputStream.close();
    }

    @Test
    public void testFileOutputStream2() throws IOException {
        try (
                OutputStream outputStream =
                        new FileOutputStream("/Users/gaoyongxiang/百度网盘/IDEA-Java/202507-java-se/chapter16/file/2.txt", true);
        ) {
            String str = "hello, world";
            outputStream.write(str.getBytes());
        }
    }


    // 练习：拷贝文件
    @Test
    public void testCopyFile() throws IOException {
        /*
            思路分析：
            1. 通过字节输入流将本地文件读取到内存中
            2. 通过字节输出流将加载到内存的文件 保存到指定位置中
            3. 这个过程是边加载边存储

         */

        try (
                FileInputStream fileInputStream = new FileInputStream("/Users/gaoyongxiang/百度网盘/IDEA-Java/202507-java-se/chapter16/file/头像.jpg");
                FileOutputStream fileOutputStream = new FileOutputStream("/Users/gaoyongxiang/百度网盘/IDEA-Java/202507-java-se/chapter16/file/1.jpg");
                ) {
            // 执行操作
            byte[] bytes = new byte[1024]; // 1 KB
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                // 读了多少 就写多少
                fileOutputStream.write(bytes, 0, len);
            }
        }
    }
}
